package main.java.indi.zyj.coderecord;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class CombinationSum3 {

    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();

    public List<List<Integer>> combinationSum3(int k, int n) {

        backtrack(1, n, k, 0);
        return res;

    }

    private void backtrack(int start, int n, int k, int sum) {
        if (sum > n) {
            return;
        }
        if (path.size() == k && sum == n) {
            res.add(new LinkedList<>(path));
            return;
        }
        for (int i = start; i <= 9 - (k - path.size()) + 1; i++) {
            path.addLast(i);
            sum += i;
            backtrack(i + 1, n, k, sum);
            sum -= i;
            path.removeLast();
        }
    }

}
